import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:o2oa_all_platform/common/extension/date_extension.dart';
import 'package:o2oa_all_platform/common/extension/string_extension.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../../common/api/x_message_assemble_communicate.dart';
import '../../../../common/models/im/im_message.dart';
import '../../../../common/routers/routes.dart';
import '../../../../common/style/color.dart';
import '../../../../common/style/theme.dart';
import '../../../../common/widgets/o2_stateless_widget.dart';
import '../im_chat/widgets/msg_body.dart';
import 'index.dart';

class ImMessageCollectionPage extends GetView<ImMessageCollectionController> {
  const ImMessageCollectionPage({Key? key}) : super(key: key);

 static void open() {
    Get.toNamed(O2OARoutes.homeImChatMessageCollection);
  }

 

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ImMessageCollectionController>(
      builder: (_) {
        return Obx(() =>Scaffold(
          appBar: controller.state.selectMode
                  ? AppBar(
                      automaticallyImplyLeading: false,
                      title: Row(
                        mainAxisAlignment: MainAxisAlignment.start,
                        children: [
                          TextButton(
                            onPressed: () => controller.clickChangeMode(),
                            child: Text('cancel'.tr,
                                style: AppTheme.whitePrimaryTextStyle),
                          ),
                          Expanded(
                              flex: 1, child: Center(child: Text('im_action_collection'.tr)))
                        ],
                      ),
                      actions: [
                        TextButton(
                            onPressed: () => controller.clickDeleteMsgs(),
                            child: Text('delete'.tr,
                                style: AppTheme.whitePrimaryTextStyle))
                      ],
                    )
                  : AppBar(title: Text("im_action_collection".tr), actions: [
                      TextButton(
                          onPressed: () => controller.clickChangeMode(),
                          child: Text('choose'.tr,
                              style: AppTheme.whitePrimaryTextStyle))
                    ]),
          body: SafeArea(
            child: _buildBody(context),
          ),
        ));
      },
    );
  }
  Widget _buildBody(BuildContext context) {
    return Container(
        color: Theme.of(context).scaffoldBackgroundColor,
        child: Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Obx(
              () => controller.state.msgList.length < 1
                  ? O2UI.noResultView(context)
                  : _messageListView(context),
            )));
  }

  Widget _messageListView(BuildContext context) {
    return Obx(() => SmartRefresher(
        enablePullDown: true,
        enablePullUp: controller.state.hasMoreData,
        controller: controller.refreshController,
        onRefresh: controller.refreshData,
        onLoading: controller.loadMore,
        child: ListView.separated(
            itemBuilder: (context, index) {
              final msgCollection = controller.state.msgList[index];
              if (msgCollection.message != null) {
                return _messageView(context, msgCollection);
              }
              return Text('empty_data'.tr);
            },
            separatorBuilder: (context, index) {
              return const Divider(
                height: 1,
              );
            },
            itemCount: controller.state.msgList.length)));
  }

  Widget _messageView(BuildContext context, IMMessageCollection msg){
    return Obx(() => controller.state.selectMode
                    ? _selectModeItemView(context, msg)
                    : _normalModeItemView(context, msg));
  }

  Widget _selectModeItemView(BuildContext context, IMMessageCollection msg) {
    return GestureDetector(
        onTap: () => {
           controller.clickChooseMsg(msg)
        },
        child: Padding(
            padding: const EdgeInsets.all(10),
            child:  Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            controller.isMessageSelected(msg)
                ? Icon(Icons.check_box_rounded,
                    size: 20, color: Theme.of(context).colorScheme.primary)
                : const Icon(
                    Icons.check_box_outline_blank,
                    size: 20,
                  ),
            const SizedBox(width: 5),
            Expanded(
              flex: 1,
                child: 
            _msgItemView(context, msg.message!))])));
  }

  Widget _normalModeItemView(BuildContext context, IMMessageCollection msg) {
    return GestureDetector(
        onTap: () => {
          controller.clickMsgItem(msg.message!)
        },
        child: Padding(
            padding: const EdgeInsets.all(10),
            child: _msgItemView(context, msg.message!)));
  }


   Widget _msgItemView(BuildContext context, IMMessage msg) {
    return Padding(
            padding: const EdgeInsets.all(10),
            child: Row(
              children: [
                SizedBox(
                  width: 50,
                  height: 50,
                  child: O2UI.personAvatar(msg.createPerson!, 25),
                ),
                const SizedBox(width: 10),
                Expanded(flex: 1, child: _msgContentView(context, msg))
              ],
            ));
  }

  Widget _msgContentView(BuildContext context, IMMessage msg) {
    final time = DateTime.tryParse(msg.createTime ?? "");

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Text(msg.createPerson?.o2NameCut() ?? '',
                style: Theme.of(context).textTheme.bodyLarge),
            const Spacer(),
            Text(time?.chatMsgShowTimeFormat() ?? '',
                style: Theme.of(context).textTheme.bodySmall)
          ],
        ),
        const SizedBox(height: 10),
        _cardMsgBody(msg),
        if (msg.quoteMessage != null) _quoteMsgView(context, msg.quoteMessage!, false),
      ],
    );
  }

  Widget _cardMsgBody(IMMessage msg) {
    final msgBody =
        MsgBodyWidget(msgBody: msg.toBody()!, isSender: false, msgId: msg.id!);
    if (msg.toBody()?.type == 'file' ||
        msg.toBody()?.type == 'audio' ||
        msg.toBody()?.type == 'location' ||
        msg.toBody()?.type == 'process' ||
        msg.toBody()?.type == 'messageHistory') {
      return Padding(
          padding: const EdgeInsets.only(right: 20),
          child: Container(
            padding: const EdgeInsets.all(10),
            decoration: BoxDecoration(
              color: AppColor.imReceiverColor,
              borderRadius: BorderRadius.circular(4),
            ),
            child: msgBody,
          ));
    }
    return msgBody;
  }

   Widget _quoteMsgView(
      BuildContext context, IMMessage quoteMessage, bool isRight) {
    String text =
        '${quoteMessage.createPerson?.o2NameCut()}: ${quoteMessage.toBody()?.conversationBodyString()}';
    if (quoteMessage.toBody()?.type == 'image') {
      text = '${quoteMessage.createPerson?.o2NameCut()}: ';
    } else if (quoteMessage.toBody()?.type == 'location') {
      text += ' ${quoteMessage.toBody()?.address}';
    } else if (quoteMessage.toBody()?.type == 'file') {
      text += ' ${quoteMessage.toBody()?.fileName}';
    } else if (quoteMessage.toBody()?.type == 'audio') {
      text += ' ${quoteMessage.toBody()?.audioDuration ?? 0} "';
    }
    return Padding(
        padding: const EdgeInsets.only(top: 2),
        child: GestureDetector(
            onTap: () {
              controller.clickMsgItem(quoteMessage);
            },
            child: Container(
              decoration: BoxDecoration(
                color: AppColor.imQuoteMsgColor,
                borderRadius: BorderRadius.circular(4),
              ),
              padding: const EdgeInsets.all(5),
             
              child: Row(
                  mainAxisAlignment:
                      isRight ? MainAxisAlignment.end : MainAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Container( 
                      constraints: const BoxConstraints(maxWidth: 200), 
                      child: Text(text, style: Theme.of(context).textTheme.bodySmall, maxLines: 3, overflow: TextOverflow.ellipsis)),
                    if (quoteMessage.toBody()?.type == 'image') _quoteMsgPictureBody(quoteMessage)
                  ]),
            )));
  }

  Widget _quoteMsgPictureBody(IMMessage quoteMessage) {
    var imageUrl = MessageCommunicationService.to
        .getIMMsgImageUrl(quoteMessage.toBody()!.fileId!);
    return Padding(
        padding: const EdgeInsets.only(left: 5),
        child: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Image.network(imageUrl,
                headers: controller.headers, width: 48, height: 48)));
  }
}
